package org.nowcoder.huawei.c200;

import java.util.*;

/**
 * 31: 5G网络建设
 */
public class HC031 {

    static class Dsu {
        // parent[i] = k ; 结点i的父结点是k
        private int[] parent;

        public Dsu(int n) {
            parent = new int[n];
            Arrays.fill(parent, -1);
        }

        public int find(int x) {
            if (parent[x] < 0) {
                return x;
            } else {
                parent[x] = find(parent[x]);
                return parent[x];
            }
        }

        public void union(int x, int y) {
            int rootX = find(x);
            int rootY = find(x);
            if (rootY != rootX) {
                parent[rootX] = rootY;
            }
        }

        public boolean isConnected(int x, int y) {
            return find(x) == find(y);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt(); // 站点数量
        int M = scanner.nextInt(); // 连接数量

        List<int[]> connections = new ArrayList<>();
        for (int i = 0; i < M; i++) {
            int x = scanner.nextInt(); // 站点x
            int y = scanner.nextInt(); // 站点y
            int cost = scanner.nextInt(); // 连接的成本
            int connected = scanner.nextInt(); // 是否已经连接
            connections.add(new int[]{x, y, cost, connected});
        }

    }

    public static void solve(List<int[]> connections, int n) {
        Dsu uf = new Dsu(n); // 创建并查集
        int totalCost = 0;

        // 首先处理已经存在的连接，不增加额外成本
        for (int[] connection : connections) {
            int x = connection[0] - 1; // 站点索引从0开始
            int y = connection[1] - 1;
            int cost = connection[2];
            int connected = connection[3];

            if (connected == 1) {
                uf.union(x, y);
            }
        }

        // 对所有未连接的边按成本从低到高排序
        connections.sort(Comparator.comparingInt(c -> c[2]));

        // 使用克鲁斯卡尔算法逐条检查未连接的边
        for (int[] connection : connections) {
            int x = connection[0] - 1;
            int y = connection[1] - 1;
            int cost = connection[2];

            // 如果添加这条边不会造成循环，则添加到MST中
            if (!uf.isConnected(x, y)) {
                uf.union(x, y);
                totalCost += cost;
            }
        }

        // 检查是否所有节点都已经连接在同一棵树上
        int root = uf.find(0);
        for (int i = 1; i < n; i++) {
            if (uf.find(i) != root) {
                System.out.println(-1);
            }
        }
        System.out.println(totalCost);
    }
}

